package inet.app.vod.activity.search;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.activity.film.IPhimDetailActivity;
import inet.app.vod.activity.fun.IFunDetailActivity;
import inet.app.vod.activity.news.INewsDetailActivity;
import inet.app.vod.adapter.FilmSuggestAdapter;
import inet.app.vod.config.AppConstants;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.FunModel;
import inet.app.vod.object.MovieModel;
import inet.app.vod.object.NewModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.util.hardware.KeyboardUtil;

public class SearchFragment extends Fragment {

	private EditText mSearchEdit;
	private ListView mSearchList;
	private BaseActivity mActivity;
	private TextView mStatus;

	private String mHomeId;
	private List<MovieModel> mSearchResult;
	private FilmSuggestAdapter mSearchAdapter;
	private String mKeyword;

	private OnItemClickListener itemSearchClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			MovieModel itemSearch = mSearchResult.get(position);
			if (mHomeId.equals(AppConstants.ID_IPHIM)
					|| mHomeId.equals(AppConstants.ID_ICLIP)) {
				// film or clip
				Bundle bundle = new Bundle();
				bundle.putSerializable("movie", itemSearch);
				bundle.putString("home_id", mHomeId);
				LaunchIntent
						.start(mActivity, IPhimDetailActivity.class, bundle);
			} else if (mHomeId.equals(AppConstants.ID_INEWS)) {
				// news
				NewModel newModel = new NewModel(itemSearch.getId(),
						itemSearch.getImg(), itemSearch.getTitle());
				Bundle bundle = new Bundle();
				bundle.putSerializable("item_new", newModel);
				LaunchIntent
						.start(mActivity, INewsDetailActivity.class, bundle);
			} else if (mHomeId.equals(AppConstants.ID_IFUN)) {
				// fun
				FunModel fun = new FunModel();
				fun.setId(itemSearch.getId());
				fun.setTitle(itemSearch.getTitle());
				fun.setViewNo(itemSearch.getNumView());
				fun.setImg(itemSearch.getImg());
				Bundle bundle = new Bundle();
				bundle.putSerializable("fun", fun);
				LaunchIntent.start(mActivity, IFunDetailActivity.class, bundle);
			}
		}
	};

	private void performSearch() {
		mKeyword = mSearchEdit.getText().toString();
		if (TextUtils.isEmpty(mKeyword)) {
			return;
		}

		// send request search
		VolleyClient.requestSearch(mHomeId, mKeyword, new VolleyListener(
				mActivity) {

			@Override
			public void onSuccess(String response) {
				Log.d("success request " + response);
				ResultJsonModel jResult = Parse.parseMovieListHot(response);
				if (jResult == null) {
					MyUtil.showDialog("Không thể tải danh sách phim gợi ý",
							mActivity);
				} else if (jResult.hasError()) {
					// error register
					String error = jResult.getError();
					MyUtil.showDialog(error, mActivity);
				} else {
					mSearchResult = (List<MovieModel>) jResult.getResult();
					showSearchResult();
				}
			}

			@Override
			public void onStart() {
				Log.d("start request search");
				mActivity.showLoading(true);
			}

			@Override
			public void onFinish() {
				Log.d("finish request search");
				mActivity.showLoading(false);
			}

			@Override
			public void onError(VolleyError error) {
				MyUtil.showDialog("Lỗi tìm kiếm (" + error.getMessage() + ")",
						mActivity);
			}
		});
	}

	private void showSearchResult() {
		if (mSearchResult == null || mSearchResult.size() == 0) {
			// no result
			if (mSearchAdapter != null) {
				mSearchAdapter.clear();
			}
			mStatus.setVisibility(View.VISIBLE);
			mStatus.setText("Không tìm thấy kết quả cho từ khóa \"" + mKeyword
					+ "\"");
		} else {
			mStatus.setVisibility(View.GONE);
			mSearchAdapter = new FilmSuggestAdapter(mActivity, 0, mSearchResult);
			mSearchList.setAdapter(mSearchAdapter);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_search, container, false);
		mSearchEdit = (EditText) view.findViewById(R.id.search_edit);
		// show button seach at keyboard
		mSearchEdit
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_SEARCH) {
							KeyboardUtil.hideSoftKeyboard(mActivity);
							performSearch();
							return true;
						}
						return false;
					}
				});

		mSearchList = (ListView) view.findViewById(R.id.search_list);
		mSearchList.setOnItemClickListener(itemSearchClick);

		String hint = "";
		if (mHomeId.equals(AppConstants.ID_IPHIM)) {
			hint = "Tìm kiếm phim";
		} else if (mHomeId.equals(AppConstants.ID_ICLIP)) {
			hint = "Tìm kiếm clip";
		} else if (mHomeId.equals(AppConstants.ID_INEWS)) {
			hint = "Tìm kiếm tin";
		} else if (mHomeId.equals(AppConstants.ID_IFUN)) {
			hint = "Tìm kiếm fun";
		}
		mSearchEdit.setHint(hint);

		mStatus = (TextView) view.findViewById(R.id.status_text);

		return view;
	}

	public static SearchFragment newInstance(String homeId) {
		Bundle bundle = new Bundle();
		bundle.putString("home_id", homeId);
		SearchFragment search = new SearchFragment();
		search.setArguments(bundle);
		return search;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mActivity = (BaseActivity) getActivity();
		this.mHomeId = getArguments().getString("home_id");
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

}
